const pool = require("../db/conn");

exports.selectRightsList = async function () {
    let sql = " SELECT "+
        "   rs_right.right_id, "+
        "   rs_right.right_name, "+
        "   rs_right.right_icon, "+
        "   rs_right.right_path, "+
        "   rs_right.right_api, "+
        "   rs_right.right_function "+
        " FROM "+
        "   rs_right ";

    let conn = await pool.getConnection();
    let [result] = await conn.execute(sql);
    conn.release();
    return result;
}

exports.selectRolesList = async function () {
    // let sql = " SELECT "+
    //     "   rs_role.role_id, "+
    //     "   rs_role.role_name "+
    //     " FROM "+
    //     "   rs_role "+
    //     " WHERE "+
    //     "   rs_role.role_system <> -1 ";

    let sql = " SELECT "+
        "   rs_role.role_id, "+
        "   rs_role.role_name, "+
        "   rs_role_right.right_function, "+
        "   rs_role_right.role_right_id, "+
        "   rs_role_right.right_id, "+
        "   rs_right.right_name "+
        " FROM "+
        "   rs_role "+
        " LEFT JOIN "+
        "   rs_role_right "+
        " ON "+
        "   rs_role.role_id = rs_role_right.role_id "+
        " LEFT JOIN "+
        "   rs_right "+
        " ON "+
        "   rs_role_right.right_id = rs_right.right_id "+
        " WHERE "+
        "   rs_role.role_system <> -1 ";

    let conn = await pool.getConnection();
    let [result] = await conn.execute(sql);
    conn.release();
    return result;
}

exports.selectRoleByName = async function (role_name) {
    let sql = " SELECT "+
        "   rs_role.role_id, "+
        "   rs_role.role_name "+
        " FROM "+
        "   rs_role "+
        " WHERE "+
        "   rs_role.role_name = ? ";

    let conn = await pool.getConnection();
    let [result] = await conn.execute(sql,[role_name]);
    conn.release();
    return result[0];
}

exports.insertRole = async function (role_name) {
    let sql = "INSERT INTO rs_role (role_name, role_system) VALUES (?, 0)";

    let conn = await pool.getConnection();
    let [{changedRows}] = await conn.execute(sql,[role_name]);
    conn.release();

    return changedRows!=0;
}

exports.deleteRoleRight = async function (role_id,right_id) {
    let sql = "DELETE FROM rs_role_right WHERE role_id = ? AND right_id = ? ";
    let conn = await pool.getConnection();
    let [{changedRows}] = await conn.execute(sql,[role_id,right_id]);
    conn.release();
    return changedRows!=0;
}

exports.insertRoleRight = async function (role_id,right_id,right_function) {
    let sql = "INSERT INTO rs_role_right (role_id, right_id,right_function) VALUES (?, ?, ?)";
    let conn = await pool.getConnection();
    let [{changedRows}] = await conn.execute(sql,[role_id,right_id,right_function]);
    conn.release();
    return changedRows!=0;
}

